package com.szcinda.call;

import com.szcinda.call.phone.CallbackData;
import com.szcinda.call.service.ExceptionContext;
import com.szcinda.call.service.TicketDetailsService;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ConcurrentLinkedDeque;

@RestController
@RequestMapping({"callback"})
public class CallController {

    private static final ConcurrentLinkedDeque<CallbackData> queue = new ConcurrentLinkedDeque<>();
    private static final ConcurrentLinkedDeque<String> queue2 = new ConcurrentLinkedDeque<>();
    private final TicketDetailsService ticketDetailsService;
    private final ExceptionContext exceptionContext;

    public CallController(TicketDetailsService ticketDetailsService, ExceptionContext exceptionContext) {
        this.ticketDetailsService = ticketDetailsService;
        this.exceptionContext = exceptionContext;
    }

    @GetMapping({"test"})
    public String hello() {
        return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }


    @PostMapping({"dataJson"})
    public void callbackJson(@RequestBody CallbackData callbackData) {
        System.out.println(callbackData);
        /*String ticketId = callbackData.getData();
        String answerTime = callbackData.getSubject().getAnswerTime();
        String createTime = callbackData.getSubject().getCreateTime();*/
        ticketDetailsService.updatePhoneCallDateTime(callbackData);
    }

    @PostMapping({"data"})
    public void callback(HttpServletRequest request) throws Exception {
        String callbackData = this.getBodyString(request);
        queue2.add(callbackData);
    }

//    @Scheduled(
//            cron = "0 0/1 * * * ? "
//    )
//    private void addToRedis() {
//        List<String> dataList = new ArrayList<>();
//
//        while (!queue2.isEmpty()) {
//            String callbackDataString = queue2.poll();
//            dataList.add(callbackDataString);
//        }
//
//        /*System.out.println(this.pattern + ":dataList size:" + dataList.size());
//        if (dataList.size() > 0) {
//            dataList.forEach((data) -> {
//                this.redisTemplate.opsForValue().set(this.pattern + UUID.randomUUID().toString(), data);
//                System.out.println(this.pattern + "********************added*********************");
//            });
//        }*/
//
//    }

    @GetMapping({"testRedis/{number}"})
    public void testRedis(@PathVariable String number) {
        int num = Integer.parseInt(number);
        int count = num * 10000;
        StopWatch stopWatch = new StopWatch("REDIS " + count + " KEY 性能测试");
        stopWatch.start("写入REDIS缓存");
    }

    @PostMapping("alarm")
    public Result<String> alarm(@RequestBody ExceptionContext.AlarmNotice alarmNotice) {
        exceptionContext.alarm(alarmNotice);
        return Result.success();
    }


    @GetMapping({"/phoneStatus"})
    public void phoneStatus(HttpServletResponse response) throws Exception {
    }

    public String getBodyString(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;

        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            char[] bodyCharBuffer = new char[1024];
            boolean var6 = false;

            int len;
            while ((len = reader.read(bodyCharBuffer)) != -1) {
                sb.append(new String(bodyCharBuffer, 0, len));
            }
        } catch (IOException var19) {
            var19.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException var18) {
                    var18.printStackTrace();
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException var17) {
                    var17.printStackTrace();
                }
            }

        }

        return sb.toString();
    }

    /*@Scheduled(
            cron = "0 0/2 * * * ? "
    )
    private void saveLog() throws Exception {
    }*/


}